package cn.yuanqiao.common.utils.poi;

import cn.yuanqiao.common.utils.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListToExclUtil {

    public static Workbook getWorkbookByList(List<String> title, List<List<String>> body, String sheetName, Map<String, Map<String,String>> dict)throws Exception{
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet(sheetName);
        HSSFRow rowTitle=sheet.createRow(0);
        Map<Integer,Map<String,String>> objectHashMap = new HashMap<>();
        for(int i = 0;i<title.size();i++){
            String s = title.get(i);
            if(dict.containsKey(s)){
                objectHashMap.put(i,dict.get(s));
            }
            rowTitle.createCell(i).setCellValue(title.get(i));
        }
        //创建单元格并设置单元格内容
        for (int i = 0;i<body.size();i++){
            List<String> list = body.get(i);
            HSSFRow rowBody=sheet.createRow(i+1);
            for(int k = 0;k<list.size();k++){
                String s = list.get(k);
                if(!StringUtils.isNotEmpty(s) || "null".equals(s)){
                    s = "";
                }else{
                    if(objectHashMap.containsKey(k)){
                        Map<String, String> map = objectHashMap.get(k);
                        s = map.get(s);
                    }
                }
                rowBody.createCell(k).setCellValue(s);
            }
        }
        return wb;
    }

    /**
     * 无字典匹配
     * @param title
     * @param body
     * @param sheetName
     * @return
     * @throws Exception
     */
    public static Workbook getWorkbookByListNoDict(List<String> title, List<List<String>> body, String sheetName)throws Exception{
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wb.createSheet(sheetName);
        HSSFRow rowTitle=sheet.createRow(0);
        for(int i = 0;i<title.size();i++){
            rowTitle.createCell(i).setCellValue(title.get(i));
        }
        //创建单元格并设置单元格内容
        for (int i = 0;i<body.size();i++){
            List<String> list = body.get(i);
            HSSFRow rowBody=sheet.createRow(i+1);
            for(int k = 0;k<list.size();k++){
                String s = list.get(k);
                if(!StringUtils.isNotEmpty(s) || "null".equals(s)){
                    s = "";
                }
                rowBody.createCell(k).setCellValue(s);
            }
        }
        return wb;
    }
}
